<template>
  <el-drawer
    class="basic-drawer"
    :model-value="visible"
    :class="classNames"
    :size="650"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @open="run"
    @closed="handleClose"
  >
    <template #header>
      <section class="flex items-center gap-x-4">
        <app-icon
          name="back"
          color="#393C40"
          @click="() => emit('update:visible', false)"
        />
        <span>日志</span>
      </section>
    </template>
    <el-button
      type="primary"
      :disabled="!isEnd"
      :icon="Download"
      class="mb-4"
      @click="handleDownload"
      >下载</el-button
    >
    <div ref="el"></div>
  </el-drawer>
</template>
<script lang="ts" setup>
import { Download } from '@element-plus/icons-vue'

import type { CertLogModel } from '@/apis/model/cert'
import { useTerminal } from '@/hooks/useTerminal'
interface IProps {
  visible: boolean
  body?: CertLogModel
}
const props = withDefaults(defineProps<IProps>(), {
  visible: false,
  body: { xterm_weight: 80, xterm_height: 80 }
})
// 刷新表格事件
interface IEmit {
  (event: 'update:visible', value: boolean): void
}
const emit = defineEmits<IEmit>()
const { el, isEnd, run, request, classNames, dispose } = useTerminal({
  api: getCertLogApi,
  body: props.body,
  immediate: false
})

/**
 * 轮询逻辑
 */
let timer: NodeJS.Timer
watchEffect(() => {
  if (props.visible) pollMessage()
})
onBeforeUnmount(() => {
  clearInterval(timer)
})
async function pollMessage() {
  timer = await setInterval(() => {
    clear()
    request(props.body)
  }, 3 * 1000)
}
const clear = watch(
  () => isEnd.value,
  val => {
    if (val) {
      clearInterval(timer)
      clear()
    }
  }
)
//弹窗关闭
const handleClose = () => {
  emit('update:visible', false)
  clearInterval(timer)
  dispose()
}
const handleDownload = () => {
  // downloadCertificateAPI(row.id).then(res => {
  //   const str = window.atob(res.zip)
  //   let n = str.length
  //   const arr8 = new Uint8Array(n)
  //   while (n--) {
  //     arr8[n] = str.charCodeAt(n)
  //   }
  //   // 创建一个 Blob 对象
  //   const blob = new Blob([arr8], { type: 'application/zip' })
  //   // 创建一个 URL 对象
  //   const url = URL.createObjectURL(blob)
  //   // 创建一个链接元素并设置相关属性
  //   const link = document.createElement('a')
  //   link.href = url
  //   link.download = `${row.domain}.zip`
  //   // 将链接元素添加到页面中并触发点击事件
  //   document.body.appendChild(link)
  //   link.click()
  //   // 清理 URL 对象
  //   URL.revokeObjectURL(url)
  //   ToastUtils.success('下载成功')
  // })
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
